﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

namespace Game
{
    public class SceneSpriteGroupEntity : CommonEntity, ISceneObjectEntity
    {
        public GameObject gameObject { get; protected set; }
        public Transform transform { get; protected set; }

        private int _id;
        private SortingGroup _sortingGroup;
        private List<SpriteRenderer> _spriteList;
        private bool _flipX;
        private bool _flipY;

        public SceneSpriteGroupEntity(int id, Transform transform)
        {
            this._id = id;
            this.transform = transform;
            this.gameObject = transform.gameObject;
            _sortingGroup = transform.GetComponent<SortingGroup>();
            _sortingGroup.sortingLayerID = Const.SortingLayerID.Scene;
            _spriteList = new List<SpriteRenderer>();
            for (int i = 0; i < transform.childCount; ++i)
            {
                SpriteRenderer spriteRenderer = transform.GetChild(i).GetComponent<SpriteRenderer>();
                if (spriteRenderer != null)
                {
                    _spriteList.Add(spriteRenderer);
                }
            }
        }

        public int GetId()
        {
            return _id;
        }
        
        public SceneObjectEntityType GetEntityType()
        {
            return SceneObjectEntityType.Sprite;
        }

        public void SetSortingOrder(int order)
        {
            _sortingGroup.sortingOrder = order;
        }

        public void SetParent(Transform parent)
        {
            transform.SetParent(parent, false);
        }

        public void SetFlipX(bool flip)
        {
            if (_flipX != flip)
            {
                _flipX = flip;
                for (int i = 0; i < _spriteList.Count; ++i)
                {
                    _spriteList[i].flipX = _flipX;
                }   
            }
        }

        public void SetFlipY(bool flip)
        {
            if (_flipY != flip)
            {
                _flipY = flip;
                for (int i = 0; i < _spriteList.Count; ++i)
                {
                    _spriteList[i].flipY = _flipY;
                }   
            }
        }

        public bool GetFlipX()
        {
            return _flipX;
        }

        public bool GetFlipY()
        {
            return _flipY;
        }

        public void Update(float deltaTime)
        {
        }
    }
}